//
//  SinaClient.m
//  share
//
//  Created by Jacob on 8/4/14.
//  Copyright (c) 2014 com.haomee. All rights reserved.
//

#import "SinaClient.h"
#import "PlatformUserMoidel.h"
#import "shareConfig.h"
@interface SinaClient()
{

}
@property (nonatomic,strong) WBAuthorizeRequest *request;
@property (nonatomic,strong) void (^successBlock)(PlatformUserMoidel *model);
@property (nonatomic,strong) void (^failedBlock)(NSString *message);
@property (nonatomic,strong) NSString *token;
@property (nonatomic,strong) void (^shareSuccess)(bool isSuccess);
#define SINA_ACCESSTOKEN_KEY    @"com.sina.access_token"
#define SINA_UID_KEY         @"com.sina.uid"
#define SINA_EXPIRES_IN_KEY @"com.sina.expires_in"
#define SINA_REMIND_IN_KEY   @"com.sina.remind_in"
#define SINA_SCREENNAME_KEY  @"com.sina.screenname"
@end

@implementation SinaClient
+ (SinaClient *)sharedInstance{
    static SinaClient *_sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[SinaClient alloc] init];

    });
    
    return _sharedInstance;
}
-(id)init
{
    self = [super init];
    if (self) {
        [WeiboSDK enableDebugMode:YES];
        [WeiboSDK registerApp:SinaAppkey];
        self.request = [WBAuthorizeRequest request];
//        if (SinaRedirectUrl.length>0) {
         self.request.redirectURI = SinaRedirectUrl;
//        }
        self.request.scope = @"all";
    }
    return self;
   
}
-(void)getUSerInfoSuccess:(void (^)(PlatformUserMoidel *))success error:(void (^)(NSString *))errorBlock
{
    self.successBlock = [success copy];
    self.failedBlock = [errorBlock copy];

         [WeiboSDK sendRequest:self.request];

}

- (void)didReceiveWeiboResponse:(WBBaseResponse *)response
{
    if ([response isKindOfClass:WBSendMessageToWeiboResponse.class])
    {
        void (^shareSuccess)(bool isSuccess) = [self.shareSuccess copy];
        if (response.statusCode == WeiboSDKResponseStatusCodeSuccess) {
            shareSuccess(YES);
        } else {
            shareSuccess(NO);
        }

    }
    else if ([response isKindOfClass:WBAuthorizeResponse.class])
    {
        if ([(WBAuthorizeResponse *)response accessToken]) {
            
        } else {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"授权失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
            return;
        }
        [[NSUserDefaults standardUserDefaults] setObject:[(WBAuthorizeResponse *)response userID] forKey:SINA_UID_KEY];
        [[NSUserDefaults standardUserDefaults] setObject:[(WBAuthorizeResponse *)response accessToken] forKey:SINA_ACCESSTOKEN_KEY];
        [[NSUserDefaults standardUserDefaults] setObject:response.userInfo[@"expires_in"] forKey:SINA_EXPIRES_IN_KEY];
        [[NSUserDefaults standardUserDefaults] setObject:response.userInfo[@"remind_in"] forKey:SINA_REMIND_IN_KEY];
        [[NSUserDefaults standardUserDefaults] synchronize];
        //登录完成 获取用户数据
        NSString *url = [NSString stringWithFormat:@"https://api.weibo.com/2/users/show.json?uid=%@&access_token=%@&count=50",[(WBAuthorizeResponse *)response userID],[(WBAuthorizeResponse *)response accessToken]];
        [WBHttpRequest requestWithAccessToken:nil url:url httpMethod:@"GET" params:nil queue:[NSOperationQueue currentQueue] withCompletionHandler:^(WBHttpRequest *httpRequest, id result, NSError *error) {
            NSDictionary *info = result;
            PlatformUserMoidel *model = [PlatformUserMoidel new];
            [[NSUserDefaults standardUserDefaults] setObject:info[@"screen_name"] forKey:SINA_SCREENNAME_KEY];
            model.userId = info[@"idstr"];
            model.nickname = info[@"name"];
            model.avatar = info[@"profile_image_url"];
            model.orginalData = info;
            if ([info[@"gender"] isEqualToString:@"m"]) {
                model.gender = @"男";
            }
            else if([info[@"gender"] isEqualToString:@"w"]){
                model.gender = @"女";
            }
            model.platform = @"Sina";
            void (^successBlock)(PlatformUserMoidel *model) = [self.successBlock copy];
            if (successBlock) {
                successBlock(model);
            }
        }];
        
    }
}
-(void)shareImage:(UIImage *)image title:(NSString *)title description:(NSString *)description andImageUrl:(NSString *)ImgUrl andurl:(NSString *)url andCompletionBlock:(void (^)(BOOL))block
{
    self.shareSuccess = [block copy];
    
    if (![WeiboSDK isWeiboAppInstalled]) {
        [self shareWithApiImage:image title:title description:description andImageUrl:ImgUrl andurl:url andCompletionBlock:block];
        return;
    }
    WBMessageObject *message = [WBMessageObject message];
    

    if (image!= nil)
    {
        WBImageObject *imageObject = [WBImageObject object];
        NSData *data = UIImageJPEGRepresentation(image, 1);
        imageObject.imageData = data;
        message.imageObject = imageObject;

        
    }
    if ([description rangeOfString:@"http"].location) {
        message.text = [NSString stringWithFormat:@"%@\n%@",title,description];
    }else
    {
        message.text = [NSString stringWithFormat:@"%@\n%@\n%@",title,description,url];
    }
    WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:message];
    request.shouldOpenWeiboAppInstallPageIfNotInstalled = NO;
    [WeiboSDK sendRequest:request];

}
-(void)shareWithApiImage:(UIImage *)image title:(NSString *)title description:(NSString *)description andImageUrl:(NSString *)ImgUrl andurl:(NSString *)url andCompletionBlock:(void (^)(BOOL))block
{
    NSString * accessTocken = [[NSUserDefaults standardUserDefaults] objectForKey:SINA_ACCESSTOKEN_KEY];
    if (accessTocken == nil || [accessTocken isEqualToString:@""]) {
        [self getUSerInfoSuccess:^(PlatformUserMoidel *model) {
            NSString *accessTocken2 = [[NSUserDefaults standardUserDefaults] objectForKey:SINA_ACCESSTOKEN_KEY];
            NSString *content = [NSString stringWithFormat:@"%@/n%@",title,description];
            NSString *content2 = [content stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            
            NSString *Posturl = [NSString stringWithFormat:@"https://api.weibo.com/2/statuses/update.json?source=%@&access_token=%@&status=%@&visible=0",SinaAppkey,accessTocken2,content2];
            
            [WBHttpRequest requestWithAccessToken:nil url:Posturl httpMethod:@"POST" params:nil queue:[NSOperationQueue currentQueue] withCompletionHandler:^(WBHttpRequest *httpRequest, id result, NSError *error) {
                void (^shareSuccess)(bool isSuccess) = [self.shareSuccess copy];
                if (error == nil) {
                    shareSuccess(YES);
                }else
                {
                    shareSuccess(NO);
                }
                
            }];
        } error:^(NSString *message) {
            
        }];
    } else {
        NSString *content = [NSString stringWithFormat:@"%@/n%@",title,description];
        NSString *content2 = [content stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSString *Posturl = [NSString stringWithFormat:@"https://api.weibo.com/2/statuses/update.json?source=%@&access_token=%@&status=%@&visible=0",SinaAppkey,accessTocken,content2];
        
        [WBHttpRequest requestWithAccessToken:nil url:Posturl httpMethod:@"POST" params:nil queue:[NSOperationQueue currentQueue] withCompletionHandler:^(WBHttpRequest *httpRequest, id result, NSError *error) {
            void (^shareSuccess)(bool isSuccess) = [self.shareSuccess copy];
            if (error == nil) {
                shareSuccess(YES);
            }else
            {
                shareSuccess(NO);
            }
            
        }];
        
    }
    
}
-(BOOL)openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
      return [WeiboSDK handleOpenURL:url delegate:self];
}
-(void)getFriendships:(void (^)(BOOL, NSArray *))block
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *tocken = [user objectForKey:SINA_ACCESSTOKEN_KEY];
    NSString *uid = [user objectForKey:SINA_UID_KEY];
    NSString *url = [NSString stringWithFormat:@"https://api.weibo.com/2/friendships/followers.json?uid=%@&access_token=%@&count=16",uid,tocken];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];

    NSData *returnData = [NSURLConnection sendSynchronousRequest:request
                                               returningResponse:nil error:nil];
    NSError *error;
    NSDictionary *info = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:&error];
    if (error) {
        block(NO,nil);
        return;
    }
    NSArray *friendshipsArray = info[@"users"];
    block(YES,friendshipsArray);
    
}


@end
